package top.hidoctor.auscultation.feature.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.reflect.TypeToken;
import com.tang.util.AppUtil;
import com.tang.util.GsonUtil;
import com.tang.util.SPUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import top.hidoctor.auscultation.R;
import top.hidoctor.auscultation.adapter.MyXinyinAdapter;
import top.hidoctor.auscultation.adapter.ShaixuanAdapter;
import top.hidoctor.auscultation.base.BaseActivity;
import top.hidoctor.auscultation.base.Constant;
import top.hidoctor.auscultation.bean.PatientLocalInfo;
import top.hidoctor.auscultation.bean.ShaixuanBean;
import top.hidoctor.auscultation.event.XinyinEvent;
import top.hidoctor.auscultation.widget.Player;

public class MyXinyinActivity extends BaseActivity implements View.OnClickListener {
    private EditText editSearch;
    private RecyclerView recycler;
    private TextView tvShaixuan;
    private DrawerLayout drawer;
    private MyXinyinAdapter adapter;
    List<PatientLocalInfo> list = new ArrayList<>();
    private List<ShaixuanBean> shaixuanBeanList = new ArrayList<>();
    private ShaixuanAdapter shaixuanAdapter;
    private RecyclerView rcCondition;
    private Button btnChongzhi, btnConfirm;
    private int type = -1;// 1 心音 2 下载
    private List<PatientLocalInfo> data;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_my_xinyin);
        EventBus.getDefault().register(this);
        initView();
        initEvent();
    }

    private void initView() {
        final Toolbar toolbar = findViewById(R.id.toolbar);
        TextView tvTitle = findViewById(R.id.tv_title);
        toolbar.setNavigationIcon(R.mipmap.ic_back_left);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
                hideSoft(toolbar);
            }
        });
        tvTitle.setText("已采集心音样本");
        editSearch = findViewById(R.id.edit_search);
        recycler = findViewById(R.id.recycler);
        tvShaixuan = findViewById(R.id.tv_shaixuan);
        drawer = findViewById(R.id.drawer);
        recycler.setLayoutManager(new LinearLayoutManager(this));
        recycler.setAdapter(adapter = new MyXinyinAdapter(R.layout.item_my_xinyin, null));
        View view = LayoutInflater.from(this).inflate(R.layout.layout_empty_list, (ViewGroup) recycler.getParent(), false);
        adapter.setEmptyView(view);
        initDrawer();
        tvShaixuan.setOnClickListener(this);
        adapter.setOnRecyclerViewItemChildClickListener(new BaseQuickAdapter.OnRecyclerViewItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                PatientLocalInfo info = (PatientLocalInfo) adapter.getData().get(position);
                switch (view.getId()) {
                    case R.id.ll:
                        if (!AppUtil.isFastClick()) {
                            startActivity(new Intent(MyXinyinActivity.this, XinyinDetailActivity.class)
                                    .putExtra("info", info));
                        }
                        break;
                    case R.id.ll_action:
                        if (TextUtils.isEmpty(info.getUserId())) {
                            startActivity(new Intent(MyXinyinActivity.this, PatientsActivity.class)
                                    .putExtra("info", info));
                        } else if (!TextUtils.isEmpty(info.getUserId()) && !info.isUpload()) {
                            startActivity(new Intent(MyXinyinActivity.this, XinyinPatientAct.class)
                                    .putExtra("info", info));
                        }
                        break;
                    default:
                        break;
                }
            }
        });

        editSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                //以下方法防止两次发送请求
                if (actionId == EditorInfo.IME_ACTION_SEND ||
                        (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    switch (event.getAction()) {
                        case KeyEvent.ACTION_UP:
                            //发送请求
                            list.clear();
                            List<PatientLocalInfo> info = new ArrayList<>();
                            if (data.size() > 0 && type != -1) {
                                for (PatientLocalInfo bean : data) {
                                    if (bean.getType() == type) {
                                        info.add(bean);
                                    }
                                }
                            } else {
                                info.addAll(data);
                            }
                            if (info.size() > 0) {
                                if (!TextUtils.isEmpty(v.getText().toString().trim())) {
                                    for (int i = 0; i < info.size(); i++) {
                                        if (info.get(i).getName().contains(v.getText().toString().trim())) {
                                            list.add(info.get(i));
                                        }
                                    }
                                } else {
                                    list.addAll(info);
                                }
                                sortList(list);
                                adapter.setNewData(list);
                            }
                            hideSoft(editSearch);
                            return true;
                        default:
                            return true;
                    }
                }
                return false;
            }
        });
    }


    private void initDrawer() {
        shaixuanBeanList.add(new ShaixuanBean(false, "心音样本", "1"));
        shaixuanBeanList.add(new ShaixuanBean(false, "文件下载", "2"));
        drawer = findViewById(R.id.drawer);
        rcCondition = findViewById(R.id.rc_condition);
        btnChongzhi = findViewById(R.id.btn_chongzhi);
        btnConfirm = findViewById(R.id.btn_confirm);
        rcCondition.setLayoutManager(new GridLayoutManager(this, 3));
        rcCondition.setAdapter(shaixuanAdapter = new ShaixuanAdapter(R.layout.item_shaixuan, shaixuanBeanList));
        btnConfirm.setOnClickListener(this);
        btnChongzhi.setOnClickListener(this);
        shaixuanAdapter.setOnRecyclerViewItemChildClickListener(new BaseQuickAdapter.OnRecyclerViewItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                List<ShaixuanBean> data = adapter.getData();
                for (int i = 0; i < data.size(); i++) {
                    data.get(i).setCheck(false);
                }
                data.get(position).setCheck(true);
                adapter.notifyDataSetChanged();
                type = position + 1;
            }
        });


    }

    @SuppressLint("NewApi")
    private void initEvent() {
        list.clear();
        //获取 本地数组文件
        String content = (String) SPUtil.get(this, Constant.LOCAL_INFO, "");
        Log.e("TAG", "initEvent: " + content);
        if (!TextUtils.isEmpty(content)) {
            data = GsonUtil.parseJson(content, new TypeToken<List<PatientLocalInfo>>() {
            });
            list.addAll(data);
            sortList(list);
            adapter.setNewData(list);
        }

    }

    private void sortList(List<PatientLocalInfo> list) {
        Collections.sort(list, new Comparator<PatientLocalInfo>() {
            public int compare(PatientLocalInfo arg0, PatientLocalInfo arg1) {
                String hits0 = String.valueOf(arg0.getTime());
                String hits1 = String.valueOf(arg1.getTime());
                if (hits1.compareTo(hits0) > 0) {
                    return 1;
                } else if (hits1.compareTo(hits0) == 0) {
                    return 0;
                } else {
                    return -1;
                }
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_shaixuan:
                drawer.openDrawer(Gravity.RIGHT);
                break;
            case R.id.btn_chongzhi:
                editSearch.setText("");
                type = -1;
                for (int i = 0; i < shaixuanAdapter.getData().size(); i++) {
                    shaixuanAdapter.getData().get(i).setCheck(false);
                }
                shaixuanAdapter.notifyDataSetChanged();
                drawer.closeDrawer(Gravity.RIGHT);
                list.clear();
                list.addAll(data);
                sortList(list);
                adapter.setNewData(list);
                break;
            case R.id.btn_confirm:
                if (data.size() > 0 && type != -1) {
                    list.clear();
                    for (PatientLocalInfo bean : data) {
                        if (bean.getType() == type) {
                            list.add(bean);
                        }
                    }
                    sortList(list);
                    adapter.setNewData(list);
                }
                drawer.closeDrawer(Gravity.RIGHT);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Player currentPlayer = adapter.getCurrentPlayer();
        if (currentPlayer != null) {
            currentPlayer.stop();
        }
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(XinyinEvent event) {
        initEvent();
    }



}
